
<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel" :showok="false">
        <div slot="toolbar">
            <a-button @click="handleUpload" type="primary" v-if="isUpload">
                {{$ti18('rxList.importBtn','导入')}}
            </a-button>
            <a-button @click="handleSubmit" type="primary" v-if="!isUpload">确定</a-button>
        </div>
        <rx-layout>
            <div class=""ImportExcelEdit slot="center">
              <rx-fit>
                <div slot="toolheader" foldbtn="false" border="false">
                  <a-form-model ref="form"  :model="mdl" :rules = "rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-row>
                      <a-col :span="12">
                        <a-form-model-item  :label="i18n('form.name','模板名称')" prop = "name":labelCol="labelCol" :wrapperCol="wrapperCol" >
                          <a-input :placeholder="i18n('form.name','模板名称','input')" v-model="mdl.name"/>
                        </a-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <a-form-model-item  :label="i18n('form.key','模板别名')" prop = "key" :labelCol="labelCol" :wrapperCol="wrapperCol">
                          <a-input :placeholder="i18n('form.key','模板别名','input')" v-model="mdl.key"/>
                        </a-form-model-item>
                      </a-col>
                    </a-row>
                    <a-row>
                      <a-col :span="12">
                        <a-form-model-item
                          class="uplaodBoxs"
                          :label="i18n('form.templateUpload','Excel模板上传')" prop = "templateId" :labelCol="labelCol" :wrapperCol="wrapperCol"
                        >
                          <a-input v-model="mdl.templateId" style="display:none;" />
                          <a-upload
                            style="width:100%"
                            accept=""
                            action="/api/api-system/system/core/sysFile/upload"
                            :multiple="false"
                            :headers="headers"
                            :file-list="fileList"
                            :before-upload="beforeFileUpload"
                            :remove="removeFile"
                            @change="handleChange"
                          >
                            <a-button style="width:100%">
                              <a-icon type="upload"/>
                              Upload
                            </a-button>
                          </a-upload>
                          <a-icon :type="loading ? 'loading' : ''" />
                        </a-form-model-item>
                      </a-col>
                        <a-col :span="12">
                            <a-form-model-item  :label="i18n('form.remarks','备注')" prop = "comment" :labelCol="labelCol" :wrapperCol="wrapperCol">
                                <a-textarea :placeholder="i18n('form.remarks','备注','input')" :rows="2" v-model="mdl.comment"/>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                  </a-form-model>
                </div>
                <a-tabs v-model="activeKey" v-if="panes.length > 0 " hide-add type="editable-card" @edit="editPane" class="rxTabs" style="min-height: 100%;" >
                  <a-tab-pane v-for="pane in panes":tab="pane.title" :key="pane.key" forceRender>
                    <div class="rxContent">
                      <import-excel-pane :ref="'pane_'+pane.key" :field= "pane.field" :title="pane.title" :conf = "pane.conf"/>
                    </div>
                  </a-tab-pane>
                </a-tabs>
              </rx-fit>

            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
    import ImportExcelApi from '@/api/system/core/importExcel'
    import {RxDialog,BaseFormModel,Dialog,Util,RxInputButton,TokenUtil} from "@lowcode/jpaas-common-lib";
    import AFormModelItem from "ant-design-vue/es/form-model/FormItem";
    import ImportExcelPane from './ImportExcelPane'
    export default {
        name: 'ImportExcelEdit',
        mixins:[BaseFormModel],
        components: {
          AFormModelItem,
          RxDialog,
          ImportExcelPane
        },
        computed: {
          dsName() {
            return this.$refs.dsName;
          },
          table() {
            return this.$refs.table;
          },
        },
        data(){
            return {
              rules: {
                  name: [{ required:true,message:this.i18n('form.name','请输入模板名称','input'), trigger: 'change' }],
                  key: [{ required:true,message:this.i18n('form.key','请输入模板别名','input'), trigger: 'change' }],
                  templateId: [{ required:true,message:this.i18n('msa.updateDesc','请上传模板'), trigger: 'change' }],
                  comment: [{ required:false,message:this.i18n('form.remarks','请输入备注','input'), trigger: 'change' }],
                  table: [{ required:false,message:this.i18n('msa.selectTable','请选择表'), trigger: 'change' }],
              },
              activeKey: 1,
              title:"",
              content:"",
              type:"",
              fileList: [],
              file: {},
              fileZipTypes:["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
              panes:[],
              field:[],
              loading:false,
              headers:{},
              isUpload: false,
              isSelectTable:"1",
              afterUpload:"1",
              }
        },

      created () {
        var token = TokenUtil.getToken();
        if (token) {
          this.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
        }
      },

        methods: {
          i18n(name,text,key){
            return this.$ti18(name,text,"ImportExcel",key);
          },
          onload_(data){
            if(!data){
              return
            }
            this.init();
          },
          init(){
            if(this.mdl.templateId != ""){
              this.reloadTableTab()
            }
          },
          get(id){
              return ImportExcelApi.get(id);
          },
          save(){
              var setting =  this.getData().setting;
              this.mdl.field = JSON.stringify(this.field);
              this.mdl.gridData = JSON.stringify(setting);
              return ImportExcelApi.save(this.mdl);
          },
          validForm(formData){
              var setting =  this.getData().setting;
              var i = 0;
              var j = 0;

              var batId = false;
              for(; i < setting.length; i++){
                  for(j = 0; j < setting[i].gridData.length; j++){
                      if(setting[i].gridData[j].isNull == false && setting[i].gridData[j].mapType == "") {
                          this.$message.error(" ' "+ setting[i].title +" ' " + this.i18n('msa.dataError','中一个不可空的字段尚未设置！'));
                          return false;
                      }
                      if(setting[i].gridData[j].mapType == "batId") {
                          batId = true;
                      }
                  }
                  if(batId == false){
                      this.$message.error(" ' "+ setting[i].title +" ' " + this.i18n('msa.batchId','尚未设置批次ID！'));
                      return false;
                  }
                  batId = false;
              }
              return true;
          },
          handleChange(info) {
            let fileList = [...info.fileList];
            fileList = fileList.slice(-1);

            if (info.file.status === 'uploading') {
              this.loading = true;
              return;
            }
            if (info.file.status === 'done') {
              var res=info.fileList[0].response;
              if(res && res.success){
                this.mdl.templateId=res.data[0].fileId;
                this.loading=false;
              }
            }
            this.fileList = fileList;
          },

          getData() {
            var setting = [];
            for (var i = 0; i < this.panes.length; i++) {
              var pane = this.panes[i];
              var set = {
                key: pane.key,
                ...this.$refs['pane_' + pane.key][0].getData()
              }
              setting.push(set);
            }
            return {
              setting: setting
            };

          },

          removeFile(info) {
            this.fileList.splice(0, 1);
            this.file = {};
            this.panes = [];
            this.isUpload = false;
          },

          beforeFileUpload(file) {
            if (!file || !file.type || this.fileZipTypes.indexOf(file.type)==-1) {
              this.$message.error(this.i18n('msa.formatError','Excel导入格式错误！'));
              return;
            }
            this.file = file;
            this.fileList.push({
              uid: file.uid,
              name: file.name,
              status: 'done',
              url: null
            });
            this.isUpload = true;
            return true;
          },


          reloadTableTab() {
            var self_ = this;
            this.field = JSON.parse(this.mdl.field);
            var rePane = JSON.parse(this.mdl.gridData);
            for (let i = 0; i < rePane.length; i++) {
              this.panes.push({
                title: rePane[i].title,
                key: rePane[i].key,
                field:self_.field[rePane[i].title],
                conf: rePane[i]
              })
            }
          },

          handleUpload() {

            const formData = new FormData();
            let timestamp = new Date().getTime();
            formData.append('file', this.file);
            formData.append("fileUid", Util.encryptWord(this.file.uid,true));
            formData.append("time", Util.encryptWord(timestamp,true));
            this.afterUpload = "2";
            this.uploadFile(formData);
          },
          uploadFile(formData) {
            let self = this;
            this.loading = true;
            ImportExcelApi.doImport(formData).then(res => {
              self.isUpload = false;
              self.loading = false;
              self.panes = [];
              self.field = res.data;
              let keyNum = 1;
              for(var key in self.field){
                self.panes.push({
                  title: key ,
                  key: keyNum,
                  field: self.field[key]
                })
                keyNum ++;
              }
              if (!res.success) {
                self.$warning({
                  title: self.$ti18('rxMsa.masWarn.delInfo','警告'),
                  content: self.$ti18('msa.importError','导入失败！',"ImportExcel"),
                });
                return;
              }
              self.$message.info(self.$ti18('msa.importSuccess','导入成功！',"ImportExcel"));
            });
          },

          editPane(targetKey, action) {
            if (action == 'remove') {
              for (var i = 0; i < this.panes.length; i++) {
                var pane = this.panes[i];
                if (pane.key == targetKey) {
                  if(i>0){
                    this.activeKey=this.panes[i-1].key;
                  }else if(i==0 && this.panes.length>1){
                    this.activeKey=this.panes[i+1].key;
                  }
                  this.panes.splice(i, 1);
                }
              }
            }
          }
        },
    }
</script script>
</style>